<template>
  <PageContainer title="医生信息管理">
    <div class="doctor-info-container">
      <el-card shadow="hover" style="margin-bottom: 20px;">
        <div class="info-header">
          <h3>个人基本信息</h3>
        </div>
        <div class="info-content">
          <el-row :gutter="40">
            <el-col :span="6" class="avatar-col">
              <div class="avatar-container">
                <el-image :src="authStore.avatar" class="avatar" fit="cover"
                  fallback="https://via.placeholder.com/150x150?text=默认头像"></el-image>
                <p class="doctor-name">{{ doctorInfo.nickName || authStore.nickName || '未设置' }}</p>
                <p class="doctor-title">{{ doctorInfo.title || '未设置' }}</p>
              </div>
            </el-col>
            <el-col :span="18">
              <el-form :model="doctorInfo" label-width="120px" class="info-form">
                <el-row :gutter="30">
                  <el-col :span="12">
                    <el-form-item label="所属医院">
                      <span class="info-value">{{ doctorInfo.hospital?.name || '-' }}</span>
                    </el-form-item>
                    <el-form-item label="所属科室">
                      <span class="info-value">{{ doctorInfo.department?.name || '-' }}</span>
                    </el-form-item>
                    <el-form-item label="专业领域">
                      <span class="info-value">{{ doctorInfo.specialty || '-' }}</span>
                    </el-form-item>
                    <el-form-item label="执业年限">
                      <span class="info-value">{{ doctorInfo.workYears || '0' }}年</span>
                    </el-form-item>
                    <el-form-item label="联系电话">
                      <span class="info-value">{{ doctorInfo.hospital?.phone || '-' }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="执业证书">
                      <el-image :src="doctorInfo.qualification" style="width: 100px; height: auto; cursor: pointer;"
                        fit="contain" @click="handlePreviewCertificate" v-if="doctorInfo.qualification">
                        <div slot="error" class="image-error">证书图片加载失败</div>
                      </el-image>
                      <span v-else>-</span>
                    </el-form-item>
                    <el-form-item label="医院地址">
                      <span class="info-value">{{ doctorInfo.hospital?.address || '-' }}</span>
                    </el-form-item>
                    <el-form-item label="医院营业时间">
                      <span class="info-value">{{ doctorInfo.hospital?.openingHours || '-' }}</span>
                    </el-form-item>
                    <el-form-item label="账号状态">
                      <el-tag type="success">正常</el-tag>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-card shadow="hover">
        <div class="info-header">
          <h3>账号安全</h3>
        </div>
        <el-form :model="securityForm" :rules="securityRules" ref="securityFormRef" label-width="120px"
          class="security-form">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="securityForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="securityForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="securityForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-dialog title="执业证书预览" :visible.sync="certificatePreviewVisible" width="600px">
      <el-image :src="doctorInfo.qualification" style="width: 100%; max-height: 80vh;" fit="contain"
        fallback="证书图片加载失败"></el-image>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import { useAuthStore } from '@/store/modules/auth'
import doctorApi from '@/api/doctor'

// 初始化路由和Pinia实例
const router = useRouter()
const authStore = useAuthStore()

// 医生信息
const doctorInfo = ref({
  doctorId: '',
  userinfoId: '',
  departmentId: '',
  title: '',
  specialty: '',
  qualification: '',
  workYears: 0,
  nickName: '',
  department: {},
  hospital: {}
})

// 账号安全表单
const securityForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 安全表单校验规则
const securityRules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== securityForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 状态变量
const certificatePreviewVisible = ref(false)
const securityFormRef = ref(null)

// 获取医生信息
const fetchDoctorInfo = async () => {
  try {
    const userinfoId = authStore.userinfoId
    if (!userinfoId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    if (!authStore.isDoctor) {
      ElMessage.error('当前账号不是医生账号，无权限访问')
      router.push('/')
      return
    }

    const res = await doctorApi.getCurrentDoctor(userinfoId)
    if (res.code === 200 && res.data) {
      doctorInfo.value = res.data
      console.log('doctorInfo:', doctorInfo.value)
    } else {
      ElMessage.error(res.message || '获取医生信息失败')
    }
  } catch (error) {
    console.error('获取医生信息异常：', error)
    ElMessage.error('获取医生信息失败，请重试')
  }
}

// 预览执业证书
const handlePreviewCertificate = () => {
  if (doctorInfo.value.qualification) {
    certificatePreviewVisible.value = true
  } else {
    ElMessage.warning('暂无执业证书图片')
  }
}

// 🔥 核心修复：修改密码（调整参数传递格式为 Form Data）
const handleChangePassword = async () => {
  try {
    // 1. 表单校验
    await securityFormRef.value.validate()

    // 2. 构造参数（与后端 @RequestParam 对应）
    const params = {
      userinfoId: authStore.userinfoId, // 从Pinia获取userinfoId
      oldPassword: securityForm.oldPassword,
      newPassword: securityForm.newPassword
    }

    // 3. 调用接口：传递 Form Data 格式（而非 JSON）
    const res = await doctorApi.changeDoctorPassword(params)

    // 4. 结果处理
    if (res.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      // 重置表单并退出登录
      securityForm.oldPassword = ''
      securityForm.newPassword = ''
      securityForm.confirmPassword = ''
      authStore.logout()
      router.push('/login')
    } else {
      ElMessage.error(res.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码异常：', error)
    ElMessage.error(error.message || '密码修改失败')
  }
}

// 页面挂载时初始化
onMounted(() => {
  fetchDoctorInfo()
})
</script>

<style scoped lang="scss">
.doctor-info-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

.info-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;

  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.info-content {
  padding: 10px 0;
}

.avatar-col {
  display: flex;
  justify-content: center;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;

  .avatar {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    border: 2px solid #f0f0f0;
  }

  .doctor-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .doctor-title {
    font-size: 14px;
    color: #666;
    padding: 2px 8px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
  }
}

.info-form {
  .info-value {
    font-size: 14px;
    color: #666;
    line-height: 1.8;
  }
}

.security-form {
  margin-top: 10px;
}

:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
}

@media (max-width: 768px) {
  .info-content .el-row {
    flex-direction: column;
  }

  .avatar-col,
  .info-form-col {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>